package com.winit.openapi.gfs.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.gfs.spi.GfsOrderDeliveryService;
import com.winit.gfs.spi.command.GfsOrderDeliverySearchCommand;
import com.winit.gfs.spi.vo.GfsOrder;
import com.winit.gfs.spi.vo.GfsOrderDeliveryVo;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * GFS订单发货处理类
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * kun.liu 	1.0  		2017-3-2 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value="/gfs/order/delivery")
public class GfsOrderDeliveryController  extends BaseController{
	
    @Resource
    private GfsOrderDeliveryService		gfsOrderDeliveryService;
    
    /**
     * 分页查询gfs订单发货列表（已发货/发货失败/带人工审核）
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            //组装参数
            GfsOrderDeliverySearchCommand searchCommand = buildDeliverySearchCommand(json);
            //调用接口
            Page<GfsOrderDeliveryVo> pageList = gfsOrderDeliveryService.queryGfsOrderDeliveryPage(searchCommand);
            Map<String, Object> data = getPageParams(pageList);
            data.put("list", pageList.getContent());
            //返回结果参数
            Map<String, Object> pageMap = new HashMap<String, Object>();
            pageMap.put("pageNo", pageList.getPageable().getPageNumber());
            pageMap.put("pageSize", pageList.getPageable().getPageSize());
            pageMap.put("totalCount", pageList.getTotalElements());
            data.put("pageParams", pageMap);
            responseMsg.setData(data);
        }else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
       
        return SUCCESS;
    }
    
    /**
     * 查询gfs订单发货明细
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "deliveryId");
            Long deliveryId = json.getLong("deliveryId");
            GfsOrderDeliveryVo gfsOrderDelivery = gfsOrderDeliveryService.getGfsOrderDeliveryDetailById(deliveryId);
            if(gfsOrderDelivery != null){
                Map<String, Object> data = buildGfsOrderDelivery(gfsOrderDelivery);
                responseMsg.setData(data);
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    private GfsOrderDeliverySearchCommand buildDeliverySearchCommand(JSONObject json){
    	GfsOrderDeliverySearchCommand searchCommand = new GfsOrderDeliverySearchCommand();
    	searchCommand.setCtx(CommandContext.getContext());
    	
        //组装参数
        Long bpartnerId = Long.valueOf(CommandContext.getContext().getUserId());
        String orderType = json.getString("orderType");
        String status = json.getString("status");
        String sellerOrderCode = json.getString("sellerOrderCode");
        String winitOrderCode = json.getString("winitOrderCode");
        String buyerFullName = json.getString("buyerFullName");
        String buyerUserId = json.getString("buyerUserId");
        String sellerUserId = json.getString("sellerUserId");
        String saleDateStart = json.getString("saleDateStart");
        String saleDateEnd = json.getString("saleDateEnd");
        String deliveryDateStart = json.getString("deliveryDateStart");
        String deliveryDateEnd = json.getString("deliveryDateEnd");
        //待人工审核页面增加收货人国家、发货仓(海外仓)/验货仓（ISP）、Winit产品等查询条件
        String buyerCountryCode = json.getString("buyerCountryCode");
        String warehouseCode = json.getString("warehouseCode");
        String winitProductCode = json.getString("winitProductCode");
        String isMerge = json.getString("isMerge");
        String paymentDateStart = json.getString("paymentDateStart");
        String paymentDateEnd = json.getString("paymentDateEnd");
        if(StringUtils.isNotBlank(paymentDateStart)){
            paymentDateStart += " 00:00:00";
            Date from = DateUtil.parse2Date(paymentDateStart, DateUtil.FULL_DATE_STRING);
            searchCommand.setPaymentDateStart(from);
        }
        if(StringUtils.isNotBlank(paymentDateEnd)){
            paymentDateEnd += " 23:59:59";
            Date end = DateUtil.parse2Date(paymentDateEnd, DateUtil.FULL_DATE_STRING);
            searchCommand.setPaymentDateEnd(end);
        }

        if(json.containsKey("platform")){
            searchCommand.setPlatform(json.getString("platform"));
        }else{
            searchCommand.setPlatform("ebay");
        }
        if(null !=isMerge){
            searchCommand.setIsMerge(isMerge);
        }
        String txStoreKey = null;
        if(json.containsKey("txStoreKey")){
            txStoreKey = json.getString("txStoreKey");
        }
        if(StringUtils.isNotEmpty(txStoreKey)){
            searchCommand.setTxStoreKey(txStoreKey);
        }
        
        if(null !=bpartnerId){
        	searchCommand.setBpartnerId(bpartnerId);
        }
        if(StringUtils.isNotEmpty(orderType)){
        	searchCommand.setOrderType(orderType);
        }
        if(StringUtils.isNotEmpty(status)){
        	searchCommand.setStatus(status);
        }
        if(StringUtils.isNotEmpty(sellerOrderCode)){
        	searchCommand.setSellerOrderCode(sellerOrderCode);
        }
        if(StringUtils.isNotEmpty(winitOrderCode)){
        	searchCommand.setWinitOrderCode(winitOrderCode);
        }
        if(StringUtils.isNotEmpty(buyerFullName)){
        	searchCommand.setBuyerFullName(buyerFullName);
        }
        if(!StringUtils.isEmpty(buyerUserId)){
        	searchCommand.setBuyerUserId(buyerUserId);
        }
        if(!StringUtils.isEmpty(sellerUserId)){
        	searchCommand.setSellerUserId(sellerUserId);
        }
        if(null != saleDateStart){
        	saleDateStart += " 00:00:00";
        	Date from = DateUtil.parse2Date(saleDateStart, DateUtil.FULL_DATE_STRING);
        	searchCommand.setSaleDateStart(from);
        }
        if(null != saleDateEnd){
        	saleDateEnd += " 23:59:59";
        	Date end = DateUtil.parse2Date(saleDateEnd, DateUtil.FULL_DATE_STRING);
        	searchCommand.setSaleDateEnd(end);
        }
        if(null != deliveryDateStart){
        	deliveryDateStart += " 00:00:00";
        	Date from = DateUtil.parse2Date(deliveryDateStart, DateUtil.FULL_DATE_STRING);
        	searchCommand.setDeliveryDateStart(from);
        }
        if(null != deliveryDateEnd){
        	deliveryDateEnd += " 23:59:59";
        	Date end = DateUtil.parse2Date(deliveryDateEnd, DateUtil.FULL_DATE_STRING);
        	searchCommand.setDeliveryDateEnd(end);
        }
        if(!StringUtils.isEmpty(buyerCountryCode)){
        	searchCommand.setBuyerCountryCode(buyerCountryCode);
        }
        if(!StringUtils.isEmpty(warehouseCode)){
        	searchCommand.setWarehouseCode(warehouseCode);
        }
        if(!StringUtils.isEmpty(winitProductCode)){
        	searchCommand.setWinitProductCode(winitProductCode);
        }
        
        Searchable<?> searchable = buildSearchablePageParams(json);
        searchable.addSort(new Sort(Direction.DESC, "updated"));
        String sort = json.getString("sort");
        String sortColumn = json.getString("sortColumn");
        //排序方式
        Direction direction = Direction.DESC;
        if ("asc".equalsIgnoreCase(sort)) {
            direction = Direction.ASC;
        }
        if(StringUtils.isNotEmpty(sort) && StringUtils.isNotEmpty(sortColumn)){
            searchable.addSort(new Sort(direction, sortColumn));
        }
        searchCommand.setSearchable(searchable);
        return searchCommand;
    }
    
    private Map<String, Object> buildGfsOrderDelivery(GfsOrderDeliveryVo deliveryVo){
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("deliveryId", deliveryVo.getDeliveryId());
        data.put("status", deliveryVo.getStatus());
        data.put("orderType", deliveryVo.getOrderType());
        data.put("sellerOrderCode", deliveryVo.getSellerOrderCode());
        data.put("winitOrderCode", deliveryVo.getWinitOrderCode());
        data.put("errorMsg", deliveryVo.getErrorMsg());
        data.put("winitProductCode", deliveryVo.getWinitProductCode());
        data.put("winitProductName", deliveryVo.getWinitProductName());
        data.put("deliveryWayCode", deliveryVo.getDeliveryWayCode());
        data.put("deliveryWayName", deliveryVo.getDeliveryWayName());
        data.put("warehouseCode", deliveryVo.getWarehouseCode());
        data.put("warehouseName", deliveryVo.getWarehouseName());
        data.put("trackingNo", deliveryVo.getTrackingNo());
        data.put("shipperAddrCode", deliveryVo.getShipperAddrCode());
        data.put("buyerUserId", deliveryVo.getBuyerUserId());
        data.put("sellerUserId", deliveryVo.getSellerUserId());
        data.put("buyerFullname", deliveryVo.getBuyerFullname());
        data.put("buyerEmail", deliveryVo.getBuyerEmail());
        data.put("buyerPhone", deliveryVo.getBuyerPhone());
        data.put("buyerCountry", deliveryVo.getBuyerCountry());
        data.put("buyerState", deliveryVo.getBuyerState());
        data.put("buyerCity", deliveryVo.getBuyerCity());
        data.put("buyerPostCode", deliveryVo.getBuyerPostCode());
        data.put("doorplateNumbers", deliveryVo.getDoorpLateNumbers());        
        data.put("buyerAddreess", deliveryVo.getBuyerAddreess2());
        data.put("buyerAddreess2", deliveryVo.getBuyerAddreess3());
        data.put("weight", deliveryVo.getWeight());
        data.put("extent", deliveryVo.getExtent());
        data.put("width", deliveryVo.getWidth());
        data.put("height", deliveryVo.getHeight());
        data.put("platform", deliveryVo.getPlatform());
        
        //gfs商品信息
        data.put("listGfsOrderDetail", deliveryVo.getGfsOrderDeliveryDetailVoList());
        
        String egdOrder = ApiConstant.IS_ACTIVE_N;
        Date gddTime = null;
        //ebay订单详情
        List<GfsOrder> ebayOrderList = deliveryVo.getEbayOrderList();
        data.put("gfsOrderId", ebayOrderList.get(0).getOrderId());
        List<Map<String, Object>> ebayInfoList = new ArrayList<Map<String, Object>>();
        if(ebayOrderList != null && ebayOrderList.size() > 0){
            Map<String, Object> ebayInfo = null;
            for(GfsOrder ebayOrder:ebayOrderList){
                ebayInfo = new HashMap<String, Object>();
                ebayInfo.put("sellerUserId", ebayOrder.getSellerUserId());
                ebayInfo.put("checkOutDate", ebayOrder.getCheckOutDate());
                ebayInfo.put("paymentDate", ebayOrder.getPaymentDate());
                ebayInfo.put("postageDate", ebayOrder.getPostageDate());
                ebayInfo.put("feedbackSent", ebayOrder.getFeedbackSent());
                ebayInfo.put("feedbackReceive", ebayOrder.getFeedbackReceive());
                ebayInfo.put("paymentReceivedDate", ebayOrder.getPaymentReceivedDate());
                ebayInfo.put("paymentMethod", ebayOrder.getPaymentMethod());
                ebayInfo.put("postedDate", ebayOrder.getPostedDate());
                ebayInfo.put("postageService", ebayOrder.getPostageService());
                ebayInfo.put("lastEmailSent", ebayOrder.getDeliveryDate());//发货时间
                ebayInfo.put("saleDate", ebayOrder.getSaleDate());
                ebayInfo.put("totalAllPrice", ebayOrder.getTotalAllPrice());
                ebayInfo.put("totalPriceCurrency", ebayOrder.getTotalPriceCurrency());
                ebayInfo.put("payPriceCurrency", ebayOrder.getPayPriceCurrency());
                ebayInfo.put("payPrice", ebayOrder.getPayPrice());
                ebayInfo.put("txStoreKey", ebayOrder.getTxStoreKey());  
                ebayInfo.put("txVSAccountID", ebayOrder.getTxVSAccountID());  
                ebayInfo.put("txShipping", ebayOrder.getTxShipping());  
                ebayInfo.put("txTax", ebayOrder.getTxTax());  
                ebayInfo.put("txHandling", ebayOrder.getTxHandling());  
                ebayInfo.put("txDiscount", ebayOrder.getTxDiscount());  
                ebayInfo.put("txInsuranceType", ebayOrder.getTxInsuranceType());
                ebayInfo.put("txCurrency", ebayOrder.getTxCurrency());
                ebayInfo.put("txMemo", ebayOrder.getTxMemo());
                ebayInfo.put("txGiftMessage", ebayOrder.getTxGiftMessage());
                ebayInfo.put("platform", ebayOrder.getPlatform());
                ebayInfo.put("ebayProductList", ebayOrder.getEbayProductList());
                ebayInfoList.add(ebayInfo);
                if(ApiConstant.IS_ACTIVE_Y.equals(ebayOrder.getEgdOrder())){
                    egdOrder = ebayOrder.getEgdOrder();
                    if(gddTime == null){
                        gddTime = ebayOrder.getGddTimeMax();
                    }else if(ebayOrder.getGddTimeMax() != null && ebayOrder.getGddTimeMax().before(gddTime)){
                        gddTime = ebayOrder.getGddTimeMax();
                    }
                }
            }
			data.put("remark", deliveryVo.getRemark());
        	data.put("vasList", deliveryVo.getVasList());
        }

        data.put("ebayInfoList", ebayInfoList);
        data.put("gddTime", gddTime);
        data.put("egdOrder", egdOrder);
        data.put("isMerge", deliveryVo.getIsMerge());
        return data;
   }
	
}
